import React, { useState, useEffect,useRef } from 'react';
import {
  AppBar,
  Toolbar,
  IconButton,
  Typography,
  TextField,
  Box,
  Menu,
  MenuItem,
  Paper,
  List,
  ListItem,
  ListItemText,
  Badge,
  Popper
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import MailIcon from '@mui/icons-material/Mail';
import { useNavigate } from 'react-router-dom';
import { getUserInfo } from '../api/user';
import { io } from 'socket.io-client';
import {BASE_URL,flask_url} from "../config";

// 临时注释掉WebSocket连接，防止错误
const socket = io(flask_url); // 改成你的 WebSocket 地址
// 创建一个模拟的socket对象，防止代码报错
// const socket = {
//   on: () => {},
//   off: () => {},
//   emit: () => {},
//   id: 'mock-socket-id'
// };

const navigationItems = [
  { label: '首页', path: '/' },
  { label: '种子列表', path: '/seeds' },
  { label: '上传种子', path: '/upload' },
  { label: '消息中心', path: '/message' },
  { label: 'VIP商店', path: '/store' }
];

function Navbar({ shown }) {
  const [name, setName] = useState('');
  const [anchorEl, setAnchorEl] = useState(null); // 头像菜单锚点
  const [msgAnchorEl, setMsgAnchorEl] = useState(null); // 消息弹窗锚点
  const [user, setUser] = useState({
    avatar: '/default/avatar.png',
    username: '游客',
  });
  const [messageList, setMessageList] = useState([]); // 收到的消息列表
  const [hasNewMessage, setHasNewMessage] = useState(false); // 是否有新消息
const [isOnIcon, setIsOnIcon] = useState(false);
const [isOnPopper, setIsOnPopper] = useState(false);




  const navigate = useNavigate();
  const userToken = localStorage.getItem('token');
// 在组件顶部定义一个关闭定时器引用
const closeTimerRef = useRef(null);
useEffect(() => {
  return () => {
    clearTimeout(closeTimerRef.current);
  };
}, []);

  // 获取用户信息
  useEffect(() => {
    if (!userToken) {
      alert('请先登录！');
      navigate('/login');
      return;
    }

    // 先尝试从localStorage获取用户信息
    try {
      const localUserInfo = JSON.parse(localStorage.getItem('user'));
      if (localUserInfo) {
        setUser(localUserInfo);
      }
    } catch (error) {
      console.error('本地用户信息解析失败:', error);
    }

    // 然后从API获取最新用户信息
    getUserInfo(userToken)
      .then(res => {
        if (res) {
          console.log('用户信息:', res);
          setUser(res);
          
          // 保存用户信息到localStorage，供其他组件使用
          try {
            localStorage.setItem('user', JSON.stringify(res.data || res));
            console.log('用户信息已保存到localStorage');
          } catch (error) {
            console.error('保存用户信息到localStorage失败:', error);
          }
        } else {
          setUser({
            avatar: '/default/avatar.png',
            username: '游客',
          });
        }
      })
      .catch(err => {
        console.error('获取用户信息失败:', err);
        setUser({
          avatar: '/default/avatar.png',
          username: '游客',
        });
      });
  }, [userToken, navigate]);

  // 监听 WebSocket 消息
  useEffect(() => {
    const currentUserId = Number(localStorage.getItem('id')); // 或其他方式获取当前用户ID
    socket.on('connect', () => {
    console.log('✅ Connected to WebSocket server with id:', socket.id);
  });

  socket.on('connect_error', (err) => {
    console.error('❌ WebSocket connect error:', err);
  });
    socket.on('receive_message', (msg) => {
  const currentUserId = Number(localStorage.getItem('id'));
  if (msg.receiver_id !== currentUserId) return;

  setMessageList(prev => {
    const hasSender = prev.some(m => m.sender_id === msg.sender_id);
    if (hasSender) return prev;
    return [...prev, msg]; // msg 中应包含 sender_name 和 sender_avatar
  });

  setHasNewMessage(true);
});


    return () => {
    socket.off('receive_message');
  };
  }, []);
 const handleOpenChat = (id,name,avatar) => {
    const userForMessage = {
      id: id,
      name: name,
      avatar: avatar,
    };
  navigate('/message', { state: { user: userForMessage } });
};
  // 搜索功能
  const handleSearch = () => {
    if (name.trim() === '') return;
    navigate(`/seeds?name=${encodeURIComponent(name)}`);
  };

  // 登录按钮点击
  const handleLoginClick = () => {
    navigate("/login");
    window.location.reload();
  };

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem("user");
    localStorage.removeItem("id");
    localStorage.removeItem("token");
    // localStorage.removeItem("first_time");
    //调试用
    setUser(null);
    setAnchorEl(null);
handleLoginClick();
  };

  // 打开头像菜单
  const handleAvatarClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  // 关闭头像菜单
  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  // 个人中心跳转
  const handleProfileClick = () => {
    navigate("/profile");
    setAnchorEl(null);
  };
useEffect(() => {
  if (!isOnIcon && !isOnPopper) {
    setMsgAnchorEl(null);
  }
}, [isOnIcon, isOnPopper]);
  // 鼠标悬停信封时打开消息提示
  const handleMsgMouseEnter = (event) => {
    setMsgAnchorEl(event.currentTarget);
    // 鼠标悬停表示看到了消息，清除新消息提示
    setHasNewMessage(false);
  };

  // 鼠标离开信封和弹窗区域时关闭提示
  // 替换原来的 handleIconMouseLeave
const handleIconMouseLeave = () => {
  closeTimerRef.current = setTimeout(() => {
    setIsOnIcon(false);
  }, 800); // 延迟300ms关闭
};

// 替换原来的 handlePopperMouseLeave
const handlePopperMouseLeave = () => {
  closeTimerRef.current = setTimeout(() => {
    setIsOnPopper(false);
  }, 800); // 延迟300ms关闭
};

// 在 mouse enter 时清除定时器，防止刚进来就被关闭
const handleIconMouseEnter = (event) => {
  clearTimeout(closeTimerRef.current);
  setIsOnIcon(true);
  setMsgAnchorEl(event.currentTarget);
  setHasNewMessage(false);
};

const handlePopperMouseEnter = () => {
  clearTimeout(closeTimerRef.current);
  setIsOnPopper(true);
};

  // 点击信封跳转消息中心，同时清除红点
  const handleMsgClick = () => {
    setHasNewMessage(false);
    navigate('/message');
  };

  // 管理控制台点击事件
  const handleAdminClick = () => {
    navigate("/admin");  // 跳转到管理控制台页面
    setAnchorEl(null);  // 关闭菜单
  };

  return (
  <AppBar
  position="static"
  sx={{
    mb: 2,
    bgcolor: '#e3c6f5', // 柔紫粉背景，或者改成 #e3f2fd（清新蓝）也可以
    boxShadow: 3,
    
    backdropFilter: 'blur(6px)',
    borderRadius: 2
  }}
>

    <Toolbar sx={{ display: 'flex', justifyContent: 'space-between' }}>
      <Typography variant="h6" sx={{
  fontWeight: 'bold',
  color: '#a64ac9',
  background: 'linear-gradient(90deg, #ff8a65, #f48fb1)',
  WebkitBackgroundClip: 'text',
  WebkitTextFillColor: 'transparent',
}}>
  🎀 TaoBitTorrent
</Typography>


      <Box display="flex" alignItems="center" gap={2}>
        {shown !== 1 && (
          <>
            <TextField
              variant="outlined"
              size="small"
              placeholder="🔍 搜索关键词"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && name.trim() !== '') {
                  handleSearch();
                }
              }}
              sx={{
                borderRadius: 5,
                backgroundColor: '#f9f9f9',
                '& .MuiOutlinedInput-root': {
                  borderRadius: 10,
                },
                '& .MuiOutlinedInput-notchedOutline': {
                  borderColor: '#ddd',
                },
                '&:hover .MuiOutlinedInput-notchedOutline': {
                  borderColor: '#1976d2',
                },
              }}
            />
            <IconButton
              color="primary"
              onClick={handleSearch}
              sx={{
                bgcolor: '#e3f2fd',
                borderRadius: 2,
                transition: 'all 0.2s',
                '&:hover': { bgcolor: '#bbdefb', transform: 'scale(1.1)' }
              }}
            >
              <SearchIcon />
            </IconButton>
          </>
        )}

        {/* 信封图标 */}
        <Box
          onMouseEnter={handleIconMouseEnter}
          onMouseLeave={handleIconMouseLeave}
          sx={{ position: 'relative', display: 'inline-flex' }}
        >
          <IconButton
            color="primary"
            onClick={handleMsgClick}
            size="large"
            sx={{ transition: '0.2s', '&:hover': { transform: 'scale(1.1)' } }}
          >
            <Badge color="error" variant="dot" invisible={!hasNewMessage}>
              <MailIcon />
            </Badge>
          </IconButton>

          <Popper
            open={Boolean(msgAnchorEl)}
            anchorEl={msgAnchorEl}
            placement="bottom-start"
            onMouseEnter={handlePopperMouseEnter}
            onMouseLeave={handlePopperMouseLeave}
          >
            <Paper
              sx={{
                width: 300,
                maxHeight: 300,
                overflowY: 'auto',
                p: 1,
                boxShadow: 5,
                borderRadius: 2,
                background: '#ffffffee',
                zIndex: 3300,  // 这里一定要加
                position: 'relative', // 保证 z-index 生效
              }}
            >
              <List dense>
                {messageList.length === 0 ? (
                  <ListItem>
                    <ListItemText primary="暂无新消息" />
                  </ListItem>
                ) : (
                  messageList
                    .slice(-5)
                    .reverse()
                    .map((msg, index) => (
                      <ListItem
                        key={index}
                        divider
                        button
                        onClick={() =>
                          handleOpenChat(msg.sender_id, msg.sender_name, msg.sender_avatar)
                        }
                        sx={{
                          cursor: 'pointer',
                          '&:hover': { bgcolor: '#f5f5f5' },
                          transition: '0.2s',
                        }}
                      >
                        <Box display="flex" alignItems="center" gap={1}>
                          <img
                            src={msg.sender_avatar || '/default/avatar.png'}
                            alt="头像"
                            style={{ width: 36, height: 36, borderRadius: '50%' }}
                          />
                          <Box>
                            <Typography variant="body2" fontWeight="bold">
                              {msg.sender_name || msg.sender_id}
                            </Typography>
                            <Typography variant="caption" color="text.secondary" noWrap maxWidth={220}>
                              {msg.content}
                            </Typography>
                          </Box>
                        </Box>
                      </ListItem>
                    ))
                )}
              </List>
            </Paper>
          </Popper>
        </Box>

        {/* 用户头像和菜单 */}
        {user ? (
          <Box display="flex" alignItems="center">
            <img
              src={user.avatar}
              alt="头像"
              style={{
                width: 40,
                height: 40,
                borderRadius: "50%",
                cursor: "pointer",
                boxShadow: '0 2px 6px rgba(0,0,0,0.15)',
                transition: 'transform 0.2s',
              }}
              onClick={handleAvatarClick}
              onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'}
              onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1.0)'}
            />
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl)}
              onClose={handleCloseMenu}
              anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
              transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            >
              <MenuItem onClick={handleProfileClick}>👤 个人中心</MenuItem>
              {user.role === 'admin' && (
                  <MenuItem onClick={handleAdminClick}>管理控制台</MenuItem>
                )}
              <MenuItem onClick={handleLogout}>🚪 退出登录</MenuItem>
            </Menu>
          </Box>
        ) : (
          <Box
            onClick={handleLoginClick}
            sx={{
              width: 40,
              height: 40,
              borderRadius: "50%",
              bgcolor: "#f0f0f0",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: 12,
              cursor: "pointer",
              boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
              transition: 'transform 0.2s',
              '&:hover': { transform: 'scale(1.1)', bgcolor: '#e0e0e0' }
            }}
          >
            登录
          </Box>
        )}
      </Box>
    </Toolbar>
  </AppBar>
);
}

export default Navbar;
